package com.devops.jarmonitor.service;

import com.devops.jarmonitor.config.MetricsManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 数据模拟服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DataSimulatorService {

    private final MetricsManager metricsManager;
    private final Random random = new Random();
    
    // 模拟开关
    private final AtomicBoolean simulationEnabled = new AtomicBoolean(false);
    
    /**
     * 启用模拟
     */
    public void enableSimulation() {
        simulationEnabled.set(true);
        log.info("✅ 数据模拟已启用");
    }
    
    /**
     * 停用模拟
     */
    public void disableSimulation() {
        simulationEnabled.set(false);
        log.info("❌ 数据模拟已停用");
    }
    
    /**
     * 获取模拟状态
     */
    public boolean isSimulationEnabled() {
        return simulationEnabled.get();
    }
    
    /**
     * 定时生成业务指标数据 - 每5秒执行
     */
    @Scheduled(fixedRate = 5000)
    public void simulateBusinessMetrics() {
        if (!simulationEnabled.get()) {
            return;
        }
        
        // 模拟订单
        simulateOrders();
        
        // 模拟支付
        simulatePayments();
        
        // 模拟登录
        simulateLogins();
        
        // 模拟系统指标
        simulateSystemMetrics();
    }
    
    /**
     * 模拟订单业务
     */
    private void simulateOrders() {
        int orderCount = random.nextInt(10) + 1;
        int failCount = random.nextInt(3);
        
        for (int i = 0; i < orderCount - failCount; i++) {
            metricsManager.incrementOrderSuccess();
            log.info("📦 订单创建成功 - OrderID: ORD{}", System.currentTimeMillis() + i);
        }
        
        for (int i = 0; i < failCount; i++) {
            metricsManager.incrementOrderFail();
            log.error("❌ 订单创建失败 - 原因: 库存不足 - OrderID: ORD{}", System.currentTimeMillis() + i);
        }
        
        // 记录API响应时间
        long responseTime = 50 + random.nextInt(200);
        metricsManager.getApiResponseTimer().record(responseTime, TimeUnit.MILLISECONDS);
    }
    
    /**
     * 模拟支付业务
     */
    private void simulatePayments() {
        int paymentCount = random.nextInt(8) + 1;
        int failCount = random.nextInt(2);
        
        for (int i = 0; i < paymentCount - failCount; i++) {
            metricsManager.incrementPaymentSuccess();
            double amount = 10 + random.nextDouble() * 990;
            log.info("💰 支付成功 - PaymentID: PAY{}, Amount: {:.2f}", 
                    System.currentTimeMillis() + i, amount);
        }
        
        for (int i = 0; i < failCount; i++) {
            metricsManager.incrementPaymentFail();
            log.error("❌ 支付失败 - 原因: 余额不足 - PaymentID: PAY{}", System.currentTimeMillis() + i);
        }
    }
    
    /**
     * 模拟登录业务
     */
    private void simulateLogins() {
        int loginCount = random.nextInt(5) + 1;
        int failCount = random.nextInt(2);
        
        for (int i = 0; i < loginCount - failCount; i++) {
            metricsManager.incrementLoginSuccess();
            log.info("🔐 用户登录成功 - Username: user{}", random.nextInt(1000));
        }
        
        for (int i = 0; i < failCount; i++) {
            metricsManager.incrementLoginFail();
            log.warn("⚠️ 用户登录失败 - 原因: 密码错误 - Username: user{}", random.nextInt(1000));
        }
    }
    
    /**
     * 模拟系统指标
     */
    private void simulateSystemMetrics() {
        // 活跃用户数 50-200
        int activeUsers = 50 + random.nextInt(150);
        metricsManager.setActiveUsers(activeUsers);
        
        // 队列大小 0-100
        int queueSize = random.nextInt(100);
        metricsManager.setQueueSize(queueSize);
        
        // 数据库连接数 5-50
        int dbConnections = 5 + random.nextInt(45);
        metricsManager.setDbConnections(dbConnections);
        
        // 数据库查询时间
        long dbQueryTime = 10 + random.nextInt(100);
        metricsManager.getDbQueryTimer().record(dbQueryTime, TimeUnit.MILLISECONDS);
        
        log.debug("📊 系统指标更新 - 活跃用户: {}, 队列大小: {}, DB连接数: {}", 
                activeUsers, queueSize, dbConnections);
    }
    
    /**
     * 定时生成异常日志 - 每30秒执行
     */
    @Scheduled(fixedRate = 30000)
    public void simulateErrorLogs() {
        if (!simulationEnabled.get()) {
            return;
        }
        
        // 随机生成各种告警关键字
        int errorType = random.nextInt(10);
        
        switch (errorType) {
            case 0:
                log.error("💥 FATAL - 数据库连接池耗尽 - ConnectionPoolExhaustedException");
                break;
            case 1:
                log.error("💥 ERROR - OOM风险 - 堆内存使用率: {}%", 85 + random.nextInt(15));
                break;
            case 2:
                log.error("💥 ERROR - 接口超时 - API: /api/v1/orders timeout after 30000ms");
                break;
            case 3:
                log.error("💥 CRITICAL - Redis连接失败 - Could not connect to Redis at 127.0.0.1:6379");
                break;
            case 4:
                log.error("💥 ERROR - 第三方服务异常 - Payment gateway returned 500");
                break;
            case 5:
                log.warn("⚠️ WARN - 慢查询检测 - SQL执行时间: {}ms - SELECT * FROM orders WHERE status = 'PENDING'", 
                        5000 + random.nextInt(5000));
                break;
            case 6:
                log.error("💥 ERROR - 消息队列积压 - Queue size: {}, threshold: 1000", 1200 + random.nextInt(500));
                break;
            case 7:
                log.error("💥 FATAL - 线程池拒绝任务 - RejectedExecutionException: Task rejected from ThreadPoolExecutor");
                break;
            case 8:
                log.error("💥 ERROR - 文件系统告警 - Disk usage: {}% on /data", 90 + random.nextInt(10));
                break;
            case 9:
                log.error("💥 CRITICAL - 服务降级触发 - Circuit breaker opened for service: payment-service");
                break;
        }
    }
    
    /**
     * 定时生成业务关键日志 - 每15秒执行
     */
    @Scheduled(fixedRate = 15000)
    public void simulateBusinessLogs() {
        if (!simulationEnabled.get()) {
            return;
        }
        
        int logType = random.nextInt(5);
        
        switch (logType) {
            case 0:
                log.info("📈 高峰流量检测 - 当前QPS: {}, 峰值: 1000", 800 + random.nextInt(300));
                break;
            case 1:
                log.info("🎯 大额交易监控 - Amount: {:.2f}, UserID: user{}", 
                        10000 + random.nextDouble() * 90000, random.nextInt(1000));
                break;
            case 2:
                log.info("🔄 批处理任务完成 - 处理记录数: {}, 耗时: {}ms", 
                        1000 + random.nextInt(9000), 5000 + random.nextInt(5000));
                break;
            case 3:
                log.info("📧 邮件发送成功 - Recipient: user{}@example.com, Type: ORDER_CONFIRMATION", 
                        random.nextInt(1000));
                break;
            case 4:
                log.info("🔔 推送通知发送 - UserID: user{}, Type: PAYMENT_SUCCESS", random.nextInt(1000));
                break;
        }
    }
}
